"""
fast api接口
"""
from pydantic import BaseModel, Field
from typing import Literal, Any, List
from fastapi import Body
from fastapi import APIRouter
from sse_starlette.sse import EventSourceResponse
from fastapi.responses import StreamingResponse
from agent.streaming_agent2 import StreamingReactAgent
from loguru import logger
import base64
import json

class Response(BaseModel):
    status: str = Field(default='0', description="状态码，0为成功，其他为失败")
    msg: Literal['success', 'error'] = Field(default='success', description='是否成功返回结果')
    data: Any = Field(default=None, description='返回的数据')
    errors: str | None = Field(default=None, description='错误说明')
    success: bool = Field(default=True, description="是否成功")

# agent = StreamingReactAgent(verbose=False, mode='plan_execute', enable_reflection=False)
agent = StreamingReactAgent(verbose=False, mode='hybrid', enable_reflection=True)
# agent = StreamingReactAgent(verbose=False, mode='react', enable_reflection=False)

async def setting_api(
    session_id: str = Body(default=None, description='用户会话session'),
    mode: str = Body(default='plan_execute', description='处理模式, 当前仅三种: react, plan_execute, or hybrid'),
    enable_reflection: bool = Body(default=False, description='是否启用反思'),
    tools: List[str] = Body(default=[], description='可用的tools列表'),
    override: bool = Body(default=False, description='是否停用之前已加载的工具')
):
    try:
        # global agent
        # agent = StreamingReactAgent(
        #     mode=mode, enable_reflection=enable_reflection
        # )
        # try:
        #     image = agent.workflow_image()
        # except Exception as e:
        #     logger.error(e)
        #     image = b''
        # tool_names = await agent.tool_manager.load_mcp_tools(config, disable_tools, override)

        agent = StreamingReactAgent(verbose=False, mode='plan_execute', enable_reflection=False)
        image = b''
        available_tools = await agent.tool_manager.load_session_tools(session_id, tools)
        result = {
            'flow_image': base64.b64encode(image),
            'available_tools': available_tools,
        }
        return Response(status='0', msg='success', data=result, success=True).model_dump()

    except Exception as e:
        logger.error(e)
        return Response(status='-1', msg='error', errors=str(e), success=False).model_dump()


async def chat_api(
    session_id: str = Body(default=None, description='用户会话session'),
    tools: List[str] = Body(default=[], description='可用的tools列表'),
    query: str = Body(default=None, description='用户提问'),
    interrupt_feedback: str = Body(default=None, description='中断事件的用户反馈信息'),
    history: List[Any] = Body(default=[], description='会话历史记录'),
    max_steps: int = Body(default=5, description='最大React迭代次数')
):
    await agent.tool_manager.load_session_tools(session_id, tools)

    events = agent.run_stream(session_id, query, interrupt_feedback, history, max_steps)

    # return StreamingResponse(
    #     (event.model_dump_json() + '\n' async for event in events),
    #     media_type="text/event-stream"
    # )

    return EventSourceResponse(
        (event.model_dump_json() + '\n' async for event in events),
        media_type="text/event-stream"
    )
